﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DataTier.Repository
{
    /// <summary>
    /// Репозиторий для аутентификации/авторизации
    /// </summary>
    public class AuthRepository : RepositoryBase
    {
        public AuthRepository()
        {

        }

        public AuthRepository(IDbConnection connection)
            : base(connection)
        {

        }


        /// <summary>
        /// Возвращает роль, применяемую к анонимному пользователю
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public Role GetAnonimusRole(int roleId)
        {
            using (var dbcontext = CreateDataContext())
            {
                var role = dbcontext.Role
                    .Include("PermissionMenu")
                    .Include("PermissionMenu.Menu")
                    .Include("PermissionMenu.Menu.MVCAction")
                    .Include("PermissionMenu.Menu.Menu1")
                    .Include("PermissionMenu.Menu.Menu2")
                    .Include("PermissionMenu.Permission")
                    //
                    .Include("PermissionState")
                    .Include("PermissionState.State")
                    .Include("PermissionState.Permission")
                    //
                    .Include("PermissionMVCAction")
                    .Include("PermissionMVCAction.MVCAction")
                    .Include("PermissionMVCAction.Permission")

                    .Where(r => r.Id == roleId).FirstOrDefault();
                return role;
            }
        }


        /// <summary>
        /// Возвращает полную информацию о пользователе и его правах доступа
        /// </summary>
        /// <param name="DomainLoginName"></param>
        /// <returns></returns>
        public User GetUserSecurityDetails(string DomainLoginName)
        {
            using (var dbcontext = CreateDataContext())
            {
                //dbcontext.ContextOptions.LazyLoadingEnabled = false;
                //dbcontext.ContextOptions.ProxyCreationEnabled = true;
                var user = dbcontext.User
                    .Include("User.RoleGroup")
                    .Include("User.RoleGroup.Role")
                    //
                    .Include("User.RoleGroup.Role.PermissionMenu")
                    .Include("User.RoleGroup.Role.PermissionMenu.Menu")
                    .Include("User.RoleGroup.Role.PermissionMenu.Menu.MVCAction")
                    .Include("User.RoleGroup.Role.PermissionMenu.Menu.Menu1")
                    .Include("User.RoleGroup.Role.PermissionMenu.Menu.Menu2")
                    .Include("User.RoleGroup.Role.PermissionMenu.Permission")
                    //
                    .Include("User.RoleGroup.Role.PermissionState")
                    .Include("User.RoleGroup.Role.PermissionState.State")
                    .Include("User.RoleGroup.Role.PermissionState.Permission")
                    //
                    .Include("User.RoleGroup.Role.PermissionMVCAction")
                    .Include("User.RoleGroup.Role.PermissionMVCAction.MVCAction")
                    .Include("User.RoleGroup.Role.PermissionMVCAction.Permission")

                    .Where(u => u.Login == DomainLoginName && u.Deleted != true).FirstOrDefault();
                return user;
            }
        }


        /// <summary>
        /// Проводит аутентификацию пользователя
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="hashPassword"></param>
        /// <returns>1-ok, 2-заблокирован, 0 - не верный логин/пароль</returns>
        public int AuthenticateUser(string userName, string hashPassword)
        {
            using (var dbcontext = CreateDataContext())
            {
                //var user = dbcontext.User
                //    .Where(
                //            u => u.Deleted != true &&
                //                u.Login.ToLower() == userName.ToLower() &&
                //                string.IsNullOrEmpty(hashPassword) ? (string.IsNullOrEmpty(u.Pass)) : u.Pass == hashPassword)
                //    .FirstOrDefault();
                
                var users = dbcontext.User.Where(u => u.Deleted != true && u.Login.ToLower() == userName.ToLower()).ToList();
                
                if (users == null || users.Count == 0)
                    return 0;

                foreach (var user in users)
                {
                    if ((string.IsNullOrEmpty(hashPassword) && string.IsNullOrEmpty(user.Pass)) || (user.Pass == hashPassword))
                    {
                        if (!user.Enabled)
                            return 2;
                        else
                            return 1;
                    }
                }
                return 0;
            }
        }



    }
}
